package com.aptemo.webetek.client.widgets.players;

import java.util.List;

import com.aptemo.webetek.client.WebetekUserServiceAsync;
import com.aptemo.webetek.client.commands.GotAsynchCallback;
import com.aptemo.webetek.client.commands.impl.GetPlayersPagingAction;
import com.aptemo.webetek.client.commands.impl.InvitationAction;
import com.aptemo.webetek.client.enums.EnumUserOrdering;
import com.aptemo.webetek.client.enums.EnumUserStatus;
import com.aptemo.webetek.client.events.DecisionEvent;
import com.aptemo.webetek.client.events.DecisionHandler;
import com.aptemo.webetek.client.events.SelectedPlayerEvent;
import com.aptemo.webetek.client.exceptions.BackendException.EErrorCodes;
import com.aptemo.webetek.client.widgets.paging.PagingPresenter;
import com.aptemo.webetek.shared.PagingResult;
import com.aptemo.webetek.shared.UserBean;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.HasWidgets;

public class PlayersPagingPresenter
		extends PagingPresenter
{

	private PlayersDisplay			display;
	private WebetekUserServiceAsync	rpcService;
	private String					teamId;
	private List<UserBean>			players;
	private HandlerManager			eventbus;

	private int						pageNo	= 0;
	private UserBean				currentUser;

	public PlayersPagingPresenter(UserBean currentUser, PlayersDisplay view, HandlerManager eventBus, WebetekUserServiceAsync rpcService, String teamId,
			String filter, int pageNo)
	{
		super(view.getPagingView(), 5);

		this.display = view;
		this.rpcService = rpcService;
		this.eventbus = eventBus;

		init(currentUser, teamId, filter, pageNo);
	}

	@Override
	public void go(HasWidgets container)
	{
		container.clear();
		container.add(display.getDisplay());
		bind();

		// 
		retrieveData(pageNo);
	}

	private void retrieveData(final int page)
	{
		final String destPage = getCursor(page);

		display.getInfoField().setText(display.translate("loading"));

		//
		GetPlayersPagingAction action = new GetPlayersPagingAction(teamId, display.getStatusFilterValue(), EnumUserOrdering.DATE_ASC, destPage, getPageSize());
		rpcService.invoke(action, new GotAsynchCallback<PagingResult<UserBean>>()
		{

			@Override
			public void onError(String message, EErrorCodes code)
			{
				display.getInfoField().setText(message);
			}

			@Override
			public void onSuccess(PagingResult<UserBean> result)
			{
				// paging staff...
				if (result.getTotalCnt() >= 0)
				{
					setPagingTotalSize(result.getTotalCnt());
				}
				pageNo = updatePaging(page, result.getCursor());

				players = result.getList();
				display.getInfoField().setText("");
				display.setData(players);
			}
		});

	}

	private void bind()
	{
		display.setStatusValue(EnumUserStatus.ACTIVE);

		display.getStatusListHandler().addChangeHandler(new ChangeHandler()
		{

			@Override
			public void onChange(ChangeEvent event)
			{
				resetPaging();
			}
		});

		display.getList().addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				int selectedRow = display.getClickedRow(event);

				if (selectedRow >= 0)
				{
					// get it from paging...
					// UserBean bet = getItem(selectedRow);
					UserBean bet = players.get(selectedRow);
					String id = bet.getKey();
					eventbus.fireEvent(new SelectedPlayerEvent(id, teamId));
				}

			}
		});

		display.getInvitationConfirmation().addDecisionHandler(new DecisionHandler()
		{

			@Override
			public void onConfirmation(DecisionEvent event)
			{
				display.getInfoField().setText(display.translate("sendingMessage"));

				// get fields...
				String email = display.getInvitationEmailField().getText();
				// TODO append owner email
				String message = display.getInvitationMessageField().getText();
				String subject = display.getInvitationSubjectField().getText();
				// invitation rpc
				InvitationAction action = new InvitationAction(teamId, email, message, subject, display.translate("farewell"));
				rpcService.invoke(action, new GotAsynchCallback<UserBean>()
				{

					@Override
					public void onError(String message, EErrorCodes code)
					{
						display.getInfoField().setText(message);
					}

					@Override
					public void onSuccess(UserBean result)
					{
						display.getInfoField().setText(display.translate("invitationSucceded"));

						retrieveData(0);
					}
				});
			}
		});
	}

	private void init(UserBean currentUser, String teamid, String filter, int pageNo)
	{
		this.currentUser = currentUser;
		this.teamId = teamid;
		this.pageNo = pageNo;

		if (filter != null && !filter.isEmpty())
		{
			EnumUserStatus status;
			try
			{
				status = EnumUserStatus.valueOf(filter);
			}
			catch (Exception e)
			{
				status = EnumUserStatus.ACTIVE;
			}
			display.setStatusValue(status);
		}

////		String message = display.getInvitationMessageField().getText();
////		// add owner email in front of message
////		message = "'" + currentUser.getEmail() + "' " + message;
//		
//		display.getInvitationMessageField().setText(message);
	}

	public void update(UserBean currentUser, String teamId, String filter, int pageNo)
	{
		init(currentUser, teamId, filter, pageNo);

		retrieveData(pageNo);
	}
}
